package com.jason.lightreader.util;

import com.jason.lightreader.entity.LoginUser;
import com.jason.lightreader.entity.User;
import com.jason.lightreader.exception.ServiceException;
import com.jason.lightreader.response.Code;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

//只能在controller方法调用过程中执行
public class SecurityContext {
    //判断当前是否为登录用户
    public static boolean isLogin() {
        return getLoginUser() != null;
    }

    //获取登录用户
    public static LoginUser getLoginUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object o = authentication.getPrincipal();
        if (o instanceof LoginUser) {
            return (LoginUser) authentication.getPrincipal();
        }
        return null;
    }

    //获取登录用户实例
    public static User getUser() {
        LoginUser loginUser = getLoginUser();
        if (loginUser != null) {
            return loginUser.getUser();
        }
        return null;
    }
}
